package org.ezplatform.office.calendar.util;



import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpsUtil {
    /**
     * 发送HTTPS请求
     * @param toURL 请求地址
     * @param data 请求参数
     * @param dateType 参数类型，“JSON”,other
     * @return
     * @throws Exception
     */
    public static String HttpsPostUtil(String toURL, String data, String dateType)
            throws Exception {
        StringBuffer bs = new StringBuffer();

        //  直接通过主机认证
        HostnameVerifier hv = new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };
        //  配置认证管理器
        TrustManager[] trustAllCerts = {new TrustAllTrustManager()};
        SSLContext sc = SSLContext.getInstance("SSL");
        SSLSessionContext sslsc = sc.getServerSessionContext();
        sslsc.setSessionTimeout(0);
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        //  激活主机认证
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        URL url = new URL(toURL);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        connection.setDoOutput(true);
        if("JSON".equalsIgnoreCase(dateType)){
            connection.setRequestProperty("Content-Type","application/json;chert=UTF-8");
        }else{
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        }
        OutputStreamWriter out = new OutputStreamWriter(
                connection.getOutputStream(), "UTF-8");
        out.write(data);
        out.flush();
        out.close();
        connection.connect();
        int code = ((HttpURLConnection) connection).getResponseCode();

        InputStream is =  null;
        if (code == 200) {
            is = connection.getInputStream(); // 得到网络返回的正确输入流
        } else {
            is = ((HttpURLConnection) connection).getErrorStream(); // 得到网络返回的错误输入流
        }
        BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));

        String l = null;
        while ((l = buffer.readLine()) != null) {
            bs.append(l);
        }
        //return bs.toString();
        return String.valueOf(bs);
    }

//    public static void main(String[] s){
//        String appid="lnsxxzx";
//        String key="2868abfeef5f4aa69421868d78f2e0ef";
//        String getTokenUrl="https://172.24.23.11:20089/mhopen/LNSLZTPT/api/oauth/getAccessToken";
//        String result="";
//        HashMap<String, Object> hashMap = new HashMap<String, Object>();
//        hashMap.put("appId",appid);
//        hashMap.put("secretKey",key);
//        String reqJson=JSONObject.toJSONString(hashMap);
//        try {
//            Map<String,Object> headers = new HashMap<String,Object>();
//            result= HttpsUtil.HttpsPostUtil(getTokenUrl, reqJson, "JSON");
//             System.out.println(result);
//            Map obj= (JSONObject) JSONObject.parse(result);
//            if("200".equals(obj.get("code")+"")){
//
//                String rdata=obj.get("data")+"";
//                Map data= (Map) JSONObject.parse(rdata);
//                result=data.get("access_token")+"";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}